package com.szt.ynb.server.router.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.szt.ynb.server.router.entity.Server;
import com.szt.ynb.server.router.repository.ServerRepositroy;

@CacheConfig(cacheNames = "serverCache")
@Service
public class ServerService {
	
	@Autowired
	private ServerRepositroy repo;
	
	@Autowired
	private LogService logService;
	
	/***
	 * 服务上线
	 * 
	 * @param id
	 */
	public void online(Long id) {
		Server server = findById(id);
		if (server == null) {
			return;
		}
		if (server.getStatus() != Server.STATUS_FORSE_OFFLINE) {
			server.setStatus(Server.STATUS_ONLINE);
			server.setUpdateDate(new Date());
			repo.save(server);
		}
		
	}
	
	/***
	 * 服务下线
	 * 
	 * @param id
	 */
	public void offline(Long id) {
		Server server = findById(id);
		if (server == null) {
			return;
		}
		if (server.getStatus() != Server.STATUS_FORSE_OFFLINE) {
			server.setStatus(Server.STATUS_OFFLINE);
			server.setUpdateDate(new Date());
			repo.save(server);
		}
		
	}
	
	/***
	 * 添加服务并且上线
	 * 
	 * @param id
	 */
	public void addServer(String url, String servername, String version) {
		Server server = new Server(servername, version, url);
		save(server);
	}
	
	public List<Server> findAllValidByServerNameAndVersion(String serviceName, String version) {
		Sort sort = new Sort(Direction.DESC, "sort");
		return repo.findByserverNameAndVersionAndStatus(serviceName, version, Server.STATUS_ONLINE, sort);
	}
	
	public Server findByServerNameAndVersionAndUrl(String serviceName, String version, String url) {
		return repo.findByServerNameAndVersionAndUrl(serviceName, version, url);
	}
	
	public List<Server> findAll() {
		Sort sort = new Sort(Direction.DESC, "updateDate");
		return repo.findAll(sort);
	}
	
	public Server findById(Long id) {
		return repo.findOne(id);
	}
	
	public Server save(Server server) {
		return repo.save(server);
	}
	
}
